package com.haoshui.service.impl;

import com.haoshui.constants.RedisCacheConstans;
import com.haoshui.domain.ResponseResult;
import com.haoshui.domain.entity.LoginUser;
import com.haoshui.domain.entity.User;
import com.haoshui.domain.vo.AdminInfoVo;
import com.haoshui.domain.vo.MenuVo;
import com.haoshui.domain.vo.UserInfoVo;
import com.haoshui.enums.AppHttpCodeEnum;
import com.haoshui.mapper.UserMapper;
import com.haoshui.service.MenuService;
import com.haoshui.service.RoleService;
import com.haoshui.service.SysLoginService;
import com.haoshui.service.UserRoleService;
import com.haoshui.utils.BeanCopyUitls;
import com.haoshui.utils.JwtUtil;
import com.haoshui.utils.RedisCache;
import com.haoshui.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SysLoginServiceImpl implements SysLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //判读是不是有用户
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户登陆失败");
        }

        //获取userId，生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        //把用户存入redis
        redisCache.setCacheObject(RedisCacheConstans.SYSTEM_LOGIN_USER_KEY +userId, loginUser);

        //封装到Map
        Map<String,String> result = new HashMap<>();
        result.put("token", jwt);

        return ResponseResult.okResult(result);
    }



    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult getInfo() {


        //从token中获得userId
        Long userId = SecurityUtils.getUserId();

        //通过userId获取roleKey
        List<String> roleKey = roleService.selectRoleKeyByUserId(userId);

        //通过userId获取permissions
        List<String> permissions = menuService.selectPermsByUserId(userId);

        //获得userInfo
        User user1 = userMapper.selectById(userId);
        //封装Vo
        UserInfoVo user = BeanCopyUitls.copyBean(user1, UserInfoVo.class);
        AdminInfoVo result = new AdminInfoVo(permissions, roleKey, user);

        return  ResponseResult.okResult(result);
    }

    @Override
    public ResponseResult getRouters() {
        //获取用户id
        Long userId = SecurityUtils.getUserId();

        //查询menuTree
        List<MenuVo> menuVos = menuService.selectMenuTreeByUserId(userId);

        return ResponseResult.okResult(menuVos);
    }

    @Override
    public ResponseResult logout() {
        //获取用户Id
        Long userId = SecurityUtils.getUserId();

        //清除redis里的登录数据
        boolean b =  redisCache.deleteObject(RedisCacheConstans.SYSTEM_LOGIN_USER_KEY + userId);

        if(b){
            return ResponseResult.okResult();
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGOUT_FAIL);
        }
    }
}
